let CryptoJs = require("crypto-js");
let iv = '1234567890123456'
let canRequest = true
import {Loading} from 'element-ui'
import Vue from 'vue'
const checkResponse = (param) => {
  if (param.hasOwnProperty('code') && param.code != 1) {
    layMsgAutoClose({type: 'e', msg: param.msg})
    if (param.code == -2) {
      canRequest = false
      setTimeout(() => {
        if (param.code == -2) {
          sessionStorage.clear()
          vueRouter.replace('/login')
          layer.closeAll()
          canRequest = true
        }
      }, 2000)
    }

    return false
  } else {
    return true
  }
}
const isNum = (param) => {
  let regPos = /^\d+(\.\d+)?$/; //非负浮点数
  let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  if (regPos.test(param) || regNeg.test(param)) {
    return true;
  } else {
    return false;
  }
}

const deepCopy = (obj) => {
  let objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === "object") {
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        //判断ojb子元素是否为对象，如果是，递归复制
        if (obj[key] && typeof obj[key] === "object") {
          objClone[key] = deepClone(obj[key]);
        } else {
          //如果不是，简单复制
          objClone[key] = obj[key];
        }
      }
    }
  }
  return objClone;
}

const validateItem = (param, name) => {
  if (isEmpty(param)) {
    let msg = name + '不能为空'
    layMsgAutoClose({type: 'e', msg: msg})
    return false
  } else {
    return true
  }
}

const layMsgAutoClose = (param) => {
  layui.use('layer', function () {
    if (!isNotEmpty(param)) {
      param = {}
    }
    let newParam = $.extend(true, {}, param)
    if (!isNotEmpty(newParam.type)) {
      newParam.type = 'c'
    }
    if (!isNotEmpty(newParam.msg)) {
      newParam.msg = "操作成功"
      if (newParam.type == 'e') {
        newParam.msg = "操作失败"
      }
    }
    if (!isNotEmpty(newParam.time)) {
      newParam.time = 1000
    }
    if (!isNotEmpty(newParam.icon)) {
      newParam.icon = 1
    }
    if (newParam.type == 'e') {
      newParam.icon = 2
    }
    newParam.zIndex = '99999999999'

    layer.msg(newParam.msg, {icon: newParam.icon});
  })
}

const autoSuccess = (success) => {
  if (!isNotEmpty(success)) {
    success = (res) => {
      if (res.code == 1) {
        layMsgAutoClose({msg: res.msg, time: 1500})
      } else {
        layMsgAutoClose({type: 'e', msg: res.msg, time: 1500})
      }
    }
  }
  return success;
}

const autoError = (error) => {
  if (!isNotEmpty(error)) {
    error = (XMLHttpRequest, status) => {
      XMLHttpRequest.abort();
      if (status == 'timeout') {//超时,status还有success,error等值的情况
        layMsgAutoClose({type: 'e', msg: '请求超时', time: 1500})
      } else if (XMLHttpRequest.status == 404) {
        layMsgAutoClose({type: 'e', msg: '请求地址有误', time: 1500})
      } else {
        let param = XMLHttpRequest.responseJSON
        layMsgAutoClose({type: 'e', msg: XMLHttpRequest.responseJSON.msg, time: 1500})
        if (param.code == -2) {
          setTimeout(() => {
            vueRouter.replace('/login')
          }, 1000)
        }
      }
    }
  }
  return error
}
/**
 *
 * @param url
 * @param type
 * @param param
 * @param success
 * @param error
 * @param loading
 * @param async
 * @param dataType
 * @param timeout
 */
const requestButton = ({button,param={},success,error,loading = true,dataType = 'json'})=>{
  let permission = button.id
  let url = button.target
  return request({
    url:url,
    param:param,
    loading:loading,
    success:success,
    error:error,
    dataType:dataType,
    permission:permission
  })
}
const request = ({url, type = 'post', permission = '', param = {}, success, error, loading = true, async = true, dataType = 'json', timeout = 30000}) => {
  let token = sessionStorage.getItem('token')
  if (isEmpty(token) && isUrlNeedToken(url)) {
    layMsgAutoClose({type: 'e', msg: '没有认证信息，请重新登录'})
    canRequest = false
    setTimeout(() => {
      canRequest = true
      vueRouter.replace('/')
    }, 2000)
    return
  }
  permission = password(permission + "::" + url);
  url = common.requestUrl.getUrl(url)

  let layer
  let index

  success = autoSuccess(success)
  error = autoError(error)
  layui.use('layer', () => {
    layer = layui.layer
    if (loading) {
      index = layer.load()
    }
    if (!canRequest) {
      return
    }
    let ajaxquest = $.ajax({
      url: url,
      type: type,
      data: param,
      async: async,
      dataType: dataType,
      timeout: timeout,
      beforeSend: function (XMLHttpRequest) {
        if (isNotEmpty(token)) {
          XMLHttpRequest.setRequestHeader("TOKEN", token);
        }
        XMLHttpRequest.setRequestHeader("PERMISSION", permission);
      },
      success: (res) => {
        if (loading) {
          layer.close(index)
        }
        if (!checkResponse(res)) {
          return false
        }
        success(res)
      },
      error: (XMLHttpRequest, status) => {
        if (loading) {
          layer.close(index)
        }
        error(XMLHttpRequest, status)
      },
    })
  })

}
const isNotEmpty = (param) => {
  if (!isNull(param) && JSON.stringify(param) != '{}' && JSON.stringify(param) != '[]' && param != null && $.trim(param) !== '') {
    return true
  } else {
    return false
  }
}

const isUrlNeedToken = url => {
  return !isUrlNotNeedToken(url)
}

const isUrlNotNeedToken = url => {
  let flag = false
  notNeedTokenUrl.forEach(u => {
    if (u == url) {
      flag = true
    }
  })
  return flag
}

const notNeedTokenUrl = [
  'sys/userInfo/login'
]
const requestUrl = {
  baseFileUrl: apiUrl + "hcsp/file/",
  baseApiUrl: apiUrl,
  getUrl: function (url) {
    return this.baseApiUrl + url;
  },
  getFileUrl: function (url) {
    return this.baseFileUrl + url;
  }
}
const isEmpty = (param) => {
  return !isNotEmpty(param)
}
const strToByte = (str) => {
  let bytes = new Array();
  let len, c;
  len = str.length;
  for (let i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if (c >= 0x010000 && c <= 0x10FFFF) {
      bytes.push(((c >> 18) & 0x07) | 0xF0);
      bytes.push(((c >> 12) & 0x3F) | 0x80);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000800 && c <= 0x00FFFF) {
      bytes.push(((c >> 12) & 0x0F) | 0xE0);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000080 && c <= 0x0007FF) {
      bytes.push(((c >> 6) & 0x1F) | 0xC0);
      bytes.push((c & 0x3F) | 0x80);
    } else {
      bytes.push(c & 0xFF);
    }
  }
  return bytes;
}
const now = () => {
  let time = new Date();
  let Y, M, D, H, m
  Y = time.getFullYear()
  M = time.getMonth() + 1
  if (M < 10) {
    M = '0' + M
  }
  D = time.getDate()
  if (D < 10) {
    D = '0' + D
  }
  H = time.getHours()
  if (H < 10) {
    H = '0' + H
  }
  m = time.getMinutes()
  if (m < 10) {
    m = '0' + m
  }
  return Y + '-' + M + '-' + D + ' ' + H + ':' + m
}
const notAutoParse=(password,time)=>{
  console.log('time',time)
  const key = CryptoJs.enc.Utf8.parse(time)
  password = CryptoJs.enc.Utf8.parse(password)
  let encrypted = CryptoJs.AES.encrypt(password, key, {
    iv: key,
    mode: CryptoJs.mode.CBC,
    padding: CryptoJs.pad.ZeroPadding
  });
  return CryptoJs.enc.Base64.stringify(encrypted.ciphertext)
}
const password = (password) => {
  const key = CryptoJs.enc.Utf8.parse(now())
  password = CryptoJs.enc.Utf8.parse(password)
  let encrypted = CryptoJs.AES.encrypt(password, key, {
    iv: key,
    mode: CryptoJs.mode.CBC,
    padding: CryptoJs.pad.ZeroPadding
  });
  return CryptoJs.enc.Base64.stringify(encrypted.ciphertext)
}
const validate = (validateData) => {
  let flag = true
  for (let i = 0; i < validateData.length; i++) {
    let item = validateData[i]
    if (!validateItem(item.key, item.msg)) {
      flag = false
      return flag
    }
  }
  return flag
}
const boxIndex = {}
const openBox = ({full=false,id, area = ['800px', '600px'], title = false, shadeClose = true, closeBtn = 1, callback = () => {}, shade = 0.3, maxmin = false}) => {
  if (isEmpty(id)) {
    layMsgAutoClose({type: 'e', msg: '弹窗不能为空'})
    return
  }
  if (id.indexOf('#') < 0) {
    id = '#' + id
  }
  let dom = $(id)
  dom.css('margin','1%')
  let success = (index) => {
    boxIndex[id] = index
  }
    layer.open({
      type: 1,
      title: title,
      closeBtn: closeBtn,
      maxmin: maxmin,
      area: area,
      shade: shade,
      shadeClose: shadeClose,
      content: dom,
      success: (layero, index) => {
        success(index)
      },
      cancel: (index, layero) => {
        callback()
        closeBox('',index)
      },
      end: () => {
        callback()
      }
    })
    if (full){
      layer.full(boxIndex[id])
    }
}

const closeBox = (id,index) => {
  if (isEmpty(index)){
    if (isEmpty(id)){
      layMsgAutoClose({type:'e',msg:'id不能为空'})
      return
    }
    if (id.indexOf('#') < 0){
      id = '#' + id
    }
    index = boxIndex[id]
    if (isEmpty(index)){
      layMsgAutoClose({type:'e',msg:'该id所属dom没有对应的弹框'})
      return
    }
  }
  layer.close(index)
  Vue.delete(boxIndex,id)
}
const uuid = () => {
  let s = [];
  let hexDigits = "0123456789abcdef";
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
  let uuid = s.join("");
  return 'leo_'+uuid
}
const genId = (idStr) => {
  return idStr + '_' + uuid()
}
const getKeys = (param)=>{
  if (typeof param != 'object'){
    layMsgAutoClose({type:'e',msg:'只能是object类型获取键'})
    return []
  }
  if (param == null || param == undefined){
    layMsgAutoClose({type:'e',msg:'对象不能为null或undefined'})
    return []
  }
  let keys = []
  for (let key in param){
    keys[keys.length] = key
  }
  return keys
}
const isNull = (param)=>{
  return param == null || param == undefined
}
const closeAllBox=()=>{
  layer.closeAll()
  for (let key in boxIndex){
    delete boxIndex[key]
  }
}
const isDomNull=(dom)=>{

}
const getFieldInTree = (
  {
    treeData,
    children='children',
    field='id',
  }
)=>{
  if (isEmpty(treeData)){
    return []
  } 
  if (isEmpty(field)){
    layMsgAutoClose({type:'e',msg:'result field can not be null'})
    return []
  } 
  let result = []
  for (let i in treeData){
    result[result.length] = treeData[i][field]
    if (isNotEmpty(treeData[i][children])){
      let childResult = $.extend(true,[],getFieldInTree({treeData:treeData[i][children],field:field}))
      for (let j = 0; j < childResult.length; j++) {
        result[result.length] = childResult[j]
      }
    }
  }
  return result
}
var socket
const socketRequest = ({open,getMessage,error,close})=>{
  if (typeof(WebSocket) === "undefined"){
    layMsgAutoClose({type:'e',msg:'您的浏览器不支持webSocket'})
    return
  }
  let token = sessionStorage.getItem('token')
  let url = wsUrl + "?token=" + token
  socket = new WebSocket(url);
  socket.onopen=()=>{
    console.log("socket连接成功")
    if (open != null){
      open()
    }
  }
  socket.onmessage = (res)=>{
    console.log(res.data)
    let _res = JSON.parse(res.data)
    if (getMessage != null){
      getMessage(_res)
    }
  }
  socket.onerror=()=>{
    console.log("socket连接错误")
    if (error != null){
      error()
    }
  }
  socket.onclose=()=>{
    console.log("socket连接关闭")
    if (close != null){
      close()
    } else{
      vueRouter.replace("/")
    }
  }
}

const sendSocketMessage=(msg={toUser:'',msg:''})=>{
  let currentUser = JSON.parse(sessionStorage.getItem("user"))
  msg.fromUser = currentUser.id
  if (socket != null){
    console.log('测试发送socket数据')
    socket.send(JSON.stringify(msg))
  }
}
const common = {

  sendSocketMessage,
  socketRequest,
  notAutoParse,
  getFieldInTree,
  closeAllBox,
  isDomNull,
  isNull,
  getKeys,
  genId,
  closeBox,
  openBox,
  requestButton,
  request,
  requestUrl,
  isNotEmpty,
  isEmpty,
  layMsgAutoClose,
  isNum,
  validateItem,
  strToByte,
  now,
  password,
  deepCopy,
  validate
}
export default common
